package in.muton.edushare.pages.user;

import in.muton.edushare.pages.coursepages.CourseAssignmentCreation;
import in.muton.edushare.panels.assignment.NoAssignmentWarningPanel;
import in.muton.edushare.panels.assignment.UserAssignmentListPanel;
import in.muton.edushare.url.EntityPageParams;
import in.muton.edushare.wicket.converters.choicerenderers.GenericRenderer;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.HashMap;
import java.util.List;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.CourseInstancesDAO;
import com.edushare.common.dao.UserAssignmentLinkDAO;
import com.edushare.common.dao.UsersDAO;
import com.edushare.common.vo.Assignments;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Enrolments;

public class UserAssignment extends UserBase {

	private Boolean isAssignee;
	private Boolean isAssigner;
	private int currentRole;
	private UserAssignmentListPanel listPanel;
	private HashMap<Integer, Integer> stats;
	private static int VIEWING_AS_TEACHER = 1;
	private static int VIEWING_AS_STUDENT = 2;
	
	public UserAssignment(PageParameters params) {
		super(params);
		isAssignee = true;
		isAssigner = true;
		
		add(JavascriptPackageResource.getHeaderContribution(UserAssignment.class, "UserAssignment.js"));

		List<CourseInstances> cilStudent = 
			new UsersDAO(getSessionORMInterface()).getCourseInstances(getLoggedInUser(), Enrolments.STUDENT);
		
		//Add audit students as well
		List<CourseInstances> cilAudit = 
			new UsersDAO(getSessionORMInterface()).getCourseInstances(getLoggedInUser(), Enrolments.OBSERVER);
		if(cilAudit!=null && !cilAudit.isEmpty()){
			cilStudent.addAll(cilAudit);
		}
		
		List<CourseInstances> cil = 
			new UsersDAO(getSessionORMInterface()).getCourseInstances(getLoggedInUser(), Enrolments.TEACHER);
		
		if(cilStudent==null || cilStudent.size()<1){
			isAssignee = false;
		}else{
			this.currentRole = VIEWING_AS_STUDENT;
		}
		
		if(cil==null || cil.size()<1){
			isAssigner = false;
		}else{
			this.currentRole = VIEWING_AS_TEACHER;
		}
		
		
		if(isAssignee && isAssigner){
			add(new ViewChoicesFrag("viewChoicePlaceholder", this));
		}else{
			add(new EmptyPanel("viewChoicePlaceholder"));
		}
		
		//Stats
		this.stats = new UserAssignmentLinkDAO(getSessionORMInterface()).userAssignmentStats(getLoggedInUser());
		add(new Label("totalStat", new PropertyModel<String>(this, "totalStats")));
		add(new Label("openStat", new PropertyModel<String>(this, "openStats")));
		add(new Label("closedStat", new PropertyModel<String>(this, "closedStats")));
		add(new Label("draftStat", new PropertyModel<String>(this, "draftStats")));
		
		//DDC
		HashMap<String, Integer> cimap = new HashMap<String, Integer>();
		
		for(CourseInstances ci: cil){
			if(
					ci.getStatus() == CourseInstances.COURSE_OPEN_LINKED_TO_BATCH || 
					ci.getStatus() == CourseInstances.COURSE_OPEN_STANDALONE){
				
				cimap.put(ci.getCourse().getCourseName(), ci.getCourseInstanceId());
			}
			
		}
		
		Integer preselected = (!cimap.isEmpty())?(Integer)cimap.values().toArray()[0]:null;
		
		final GenericRenderer<Integer> gr = new GenericRenderer<Integer>(cimap, preselected);
		WebMarkupContainer assnCreateBox = new WebMarkupContainer("assnCreateBox");
		final Form<Void> form = new Form<Void>("courseSelectionForm"){
			@Override
			protected void onSubmit() {
				CourseInstances ci = new CourseInstancesDAO(getSessionORMInterface()).getCourseInstanceById(gr.getSelection());
				setResponsePage(
						CourseAssignmentCreation.class, 
						EntityPageParams.getParams(new CayenneModel<Courses>(ci.getCourse())));
			}
		};
		
		DropDownChoice<String> courseChoices = new DropDownChoice<String>("courseChoices",gr.getModel(),gr.getOptions(),gr);
		Button gotoAsnBtn = new Button("gotoAssnBtn");
		WebMarkupContainer warnNoCourse = new WebMarkupContainer("warnNoCourse");
		
		if(cimap.isEmpty()){
			courseChoices.setEnabled(false);
			gotoAsnBtn.setEnabled(false);
		}else{
			warnNoCourse.setVisible(false);
		}
		
		form.add(warnNoCourse);
		form.add(courseChoices);
		form.add(gotoAsnBtn);
		assnCreateBox.add(form);
		
		add(assnCreateBox);
		if(!isAssigner)
			assnCreateBox.setVisible(false);
		
		loadPanel();
	}
	
	public int getTotalStats(){
		return getOpenStats()+ getClosedStats() + getDraftStats();
	}
	
	public int getOpenStats(){
		if(this.stats.get(Assignments.ASSIGNMENT_STATUS_OPEN)!=null)
			return this.stats.get(Assignments.ASSIGNMENT_STATUS_OPEN);
		else
			return 0;
	}
	
	public int getClosedStats(){
		if(this.stats.get(Assignments.ASSIGNMENT_STATUS_CLOSED)!=null)
			return this.stats.get(Assignments.ASSIGNMENT_STATUS_CLOSED);
		else
			return 0;
	}
	
	public int getDraftStats(){
		if(this.stats.get(Assignments.ASSIGNMENT_STATUS_DRAFT)!=null)
			return this.stats.get(Assignments.ASSIGNMENT_STATUS_DRAFT);
		else
			return 0;
	}
	
	private void loadPanel() {
		if(currentRole == VIEWING_AS_TEACHER){
			this.listPanel = new UserAssignmentListPanel("assnListing", UserAssignmentListPanel.LIST_TYPE.LIST_AS_ASSIGNER);
			add(listPanel);
		}else if(currentRole == VIEWING_AS_STUDENT){
			this.listPanel = new UserAssignmentListPanel("assnListing", UserAssignmentListPanel.LIST_TYPE.LIST_AS_ASSIGNEE);
			add(listPanel);
		}else{
//			add(new EmptyPanel("assnListing"));
			add(new NoAssignmentWarningPanel("assnListing", this));
		}
	}
	
	@Override
	public String getActivePage() {
		return "UserAssignments";
	}

	@Override
	public String getPageTitle() {
		return "Assignments | " + getModel().getObject().getCompleteUserName()+ " | " 
			+ ApplicationConstants.APPLICATION_NAME;
	}

	@Override
	public String getUserRole() {
		// TODO Auto-generated method stub
		return " : Assignments";
	}
	
	/** view choices fragment */
	public class ViewChoicesFrag extends Fragment{
		Label currentlyShowing;
		Label toYou = new Label("currentlyShowing", "Assignments assigned to you.");
		Label byYou = new Label("currentlyShowing", "Assignments created by you.");
		
		public ViewChoicesFrag(String id, MarkupContainer markupProvider) {
			super(id, "viewChoiceFrag", markupProvider);
			if(currentRole == UserAssignment.VIEWING_AS_STUDENT){
				currentlyShowing = toYou;
			}else{
				currentlyShowing = byYou;
			}
			add(currentlyShowing);
			Form<Void> choiceForm = new Form<Void>("choiceForm");
			add(choiceForm);
			choiceForm.add(
					new SubmitLink("assnToMe"){
						public void onSubmit() {
							UserAssignment.this.currentRole = VIEWING_AS_STUDENT;
							UserAssignmentListPanel ualp = new UserAssignmentListPanel("assnListing", UserAssignmentListPanel.LIST_TYPE.LIST_AS_ASSIGNEE);
							UserAssignment.this.listPanel.replaceWith(ualp);
							UserAssignment.this.listPanel = ualp;
							currentlyShowing.replaceWith(toYou);
							currentlyShowing = toYou;
						};
					}
			);
			
			choiceForm.add(
					new SubmitLink("assnByMe"){
						public void onSubmit() {
							UserAssignment.this.currentRole = VIEWING_AS_TEACHER;
							UserAssignmentListPanel ualp = new UserAssignmentListPanel("assnListing", UserAssignmentListPanel.LIST_TYPE.LIST_AS_ASSIGNER);
							UserAssignment.this.listPanel.replaceWith(ualp);
							UserAssignment.this.listPanel = ualp;
							currentlyShowing.replaceWith(byYou);
							currentlyShowing = byYou;
						};
					}
			);
		}
		
	}

}
